package com.wang.jmonkey.gateway.handler.auth.authorization;

import com.alibaba.fastjson.JSONObject;
import com.wang.jmonkey.common.result.HttpResult;
import org.apache.http.HttpStatus;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;

/**
 * @Description 自定义鉴权失败时的处理逻辑，401未授权异常处理
 * @Author HeJiawang
 * @Date 2021/5/31 13:18
 */
public class AuthenticationEntryPointHandler implements ServerAuthenticationEntryPoint {

    @Override
    public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException ex) {
        HttpResult<Void> result = new HttpResult<Void>()
                .setSuccess(false)
                .setCode(HttpStatus.SC_UNAUTHORIZED)
                .setMsg(ex.getMessage());

        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        DataBufferFactory dataBufferFactory = response.bufferFactory();
        DataBuffer buffer = dataBufferFactory.wrap(JSONObject.toJSONString(result).getBytes(Charset.defaultCharset()));
        return response.writeWith(Mono.just(buffer))
                .doOnError((error) -> DataBufferUtils.release(buffer));
    }
}
